package org.sixtynine.stock.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.sixtynine.stock.Constants.CommonData;
import org.sixtynine.stock.ReturnData;
import org.sixtynine.stock.dto.GridPramDTO;
import org.sixtynine.stock.dto.Page;
import org.sixtynine.stock.entity.BaseEntity;
import org.sixtynine.stock.entity.Dividend;
import org.sixtynine.stock.model.FileUploadForm;
import org.sixtynine.stock.model.LoadingSearchCriteria;
import org.sixtynine.stock.service.DividendService;
import org.sixtynine.stock.service.GenericService;
import org.sixtynine.stock.service.content.DataManagerService;
import org.sixtynine.stock.service.file.ExcelProcessorFactory;
import org.sixtynine.stock.service.file.FileDataService;
import org.sixtynine.stock.util.SessionBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Thilan this class handle daily share data
 */

@Controller
@SessionAttributes
public class DividendController extends BackEndAuthController {

	/** TODO configure */
	private int RECORDS_PER_PAGE = 10;

	@Autowired
	private GenericService genericService;

	@Autowired
	private DividendService dividendService;

	@Autowired
	private FileDataService fileDataService;

	@Autowired
	DataManagerService dataManagerService;

	@RequestMapping(value = "/admin/dividend/search")
	public ModelAndView search(@ModelAttribute LoadingSearchCriteria criteria) {
		ModelAndView modelAndView = new ModelAndView("/admin/dividend/list");
		loadData(1, -1, criteria.getCompanyId(), criteria.getFromDate(),
				criteria.getToDate(), modelAndView, criteria);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/dividend/add")
	public ModelAndView addDividend(HttpServletRequest request) {
		ModelAndView modelAndView = null;
		boolean userLogged;
		SessionBean sessionBean = SessionBean.getInstance(request);
		if (sessionBean.getUser() != null) {
			userLogged = true;
			modelAndView = new ModelAndView("/admin/dividend/add");
			modelAndView.addObject("dividend", new Dividend());
			List<BaseEntity> compaies = dataManagerService
					.getData(CommonData.COMPANY.toString());
			modelAndView.addObject("companyMap", compaies);
			modelAndView.addObject("userLogged", userLogged);
		} else {
			// TODO show an error message
			modelAndView = new ModelAndView("/login/login");
		}

		return modelAndView;
	}

	@RequestMapping(value = "/admin/dividend/add/company_process")
	public ModelAndView addingDividendDataByCompany(
			@ModelAttribute("uploadFile") FileUploadForm uploadFile) {
		ModelAndView modelAndView = null;
		modelAndView = new ModelAndView("/admin/dividend/add");
		modelAndView.addObject("dividend", new Dividend());

		MultipartFile multipartFile = uploadFile.getFile();
		ReturnData<String> fileSaveReturnData = fileDataService.saveFile(
				multipartFile,
				ExcelProcessorFactory.FILE_TYPE_COMPANY_DIVIDEND_DATA_LIST,
				null);

		StringBuilder message = new StringBuilder();
		if (fileSaveReturnData._isSuccess()) {
			// if success, process it
			ReturnData<List<? extends BaseEntity>> returnData = fileDataService
					.process(
							multipartFile.getOriginalFilename(),
							ExcelProcessorFactory.FILE_TYPE_COMPANY_DIVIDEND_DATA_LIST);
			if (returnData._isSuccess()) {
				message.append("file " + multipartFile.getOriginalFilename()
						+ " uploaded and inserted successfully");
				modelAndView = new ModelAndView("/admin/dividend/list");

				loadData(1, -1, -1, null, null, modelAndView, null);

			} else {
				message.append(returnData.getMsg());
			}
		} else {
			message.append(fileSaveReturnData.getMsg());
		}
		modelAndView.addObject("message", message);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/dividend/add/process")
	public ModelAndView addingDividend(@ModelAttribute Dividend dividend,
			BindingResult result) {

		ModelAndView modelAndView = null;
		if (!result.hasErrors()) {

			genericService.saveOrUpdate(dividend);
			modelAndView = new ModelAndView("/admin/dividend/list");

			String message = "Data is successfully added.";
			modelAndView.addObject("message", message);

			return modelAndView;
		} else {
			modelAndView = new ModelAndView("/admin/dividend/add");
		}

		loadData(1, -1, dividend.getCompany().getId(), dividend.getDate(),
				dividend.getDate(), modelAndView, null);
		return modelAndView;

	}

	@RequestMapping(value = "/admin/dividend/list")
	public ModelAndView listOfDividendData(
			HttpServletRequest request,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "totalRecords", required = false) Integer totalRecords) {

		ModelAndView modelAndView = null;
		boolean userLogged;
		SessionBean sessionBean = SessionBean.getInstance(request);
		if (sessionBean.getUser() != null) {
			userLogged = true;
			modelAndView = new ModelAndView("/admin/dividend/list");
			loadData(page, totalRecords, -1, null, null, modelAndView, null);

			modelAndView.addObject("userLogged", userLogged);

		} else {
			// TODO show an error message
			modelAndView = new ModelAndView("/login/login");
		}
		return modelAndView;
	}

	/**
	 * load data
	 * 
	 * @param page
	 * @param totalRecords
	 * @param companyId
	 * @param fromDate
	 * @param toDate
	 * @param modelAndView
	 */
	private void loadData(Integer page, Integer totalRecords, int companyId,
			Date fromDate, Date toDate, ModelAndView modelAndView,
			LoadingSearchCriteria criteria) {
		GridPramDTO gridPramDTO = new GridPramDTO();
		gridPramDTO.setRows(RECORDS_PER_PAGE);
		if (page != null) {
			gridPramDTO.setPage(page);
		} else {
			gridPramDTO.setPage(1);
		}
		if (totalRecords != null) {
			gridPramDTO._setTotalNumberOfRecords(totalRecords);
		}

		Page<Dividend> dividendDataPage = dividendService.searchDividend(
				companyId, fromDate, toDate, gridPramDTO);
		modelAndView.addObject("dividendDataPage", dividendDataPage);

		List<BaseEntity> compaies = dataManagerService
				.getData(CommonData.COMPANY.toString());

		modelAndView.addObject("companyMap", compaies);
		if (criteria == null) {
			criteria = new LoadingSearchCriteria();

			criteria.setCompanyId(companyId);
			criteria.setFromDate(fromDate);
			criteria.setToDate(toDate);
		}
		modelAndView.addObject("criteria", criteria);

	}

	@RequestMapping(value = "/admin/dividend/edit/{id}", method = RequestMethod.GET)
	public ModelAndView editDividend(HttpServletRequest request,
			@PathVariable Integer id) {
		boolean userLogged;
		ModelAndView modelAndView = null;
		SessionBean sessionBean = SessionBean.getInstance(request);
		if (sessionBean.getUser() != null) {
			userLogged = true;
			modelAndView = new ModelAndView("/admin/dividend/edit");
			BaseEntity dividend = genericService.findById(id, Dividend.class);
			modelAndView.addObject("dividend", dividend);
			List<BaseEntity> compaies = dataManagerService
					.getData(CommonData.COMPANY.toString());
			modelAndView.addObject("companyMap", compaies);
			modelAndView.addObject("userLogged", userLogged);
		} else {
			// TODO show an error message
			modelAndView = new ModelAndView("/login/login");
		}

		return modelAndView;
	}

	@RequestMapping(value = "/admin/dividend/edit/{id}", method = RequestMethod.POST)
	public ModelAndView edditingDividend(@ModelAttribute Dividend dividend,
			@PathVariable Integer id) {

		genericService.saveOrUpdate(dividend);
		ModelAndView modelAndView = new ModelAndView("/admin/dividend/list");
		loadData(1, -1, dividend.getCompany().getId(), dividend.getDate(),
				dividend.getDate(), modelAndView, null);

		String message = "Record successfully updated.";
		modelAndView.addObject("message", message);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/dividend/delete/{id}", method = RequestMethod.GET)
	public ModelAndView deleteDividend(@PathVariable Integer id) {

		genericService.delete(id, Dividend.class);
		ModelAndView modelAndView = new ModelAndView("/admin/dividend/list");

		loadData(1, -1, -1, null, null, modelAndView, null);

		String message = "Record successfully deleted.";
		modelAndView.addObject("message", message);
		return modelAndView;
	}

}
